// Profiler
// (c) jimon game studio

#include "CProfiler.h"
#include "ITimer.h"

namespace je
{
	namespace core
	{
		IMPLEMENT_SINGLETON(Profiler,JE_ENGINE_FUNCTION_CALL)

		//! Constructor
		CProfiler::CProfiler()
		{
			SetProfiler(this);
			SetAutoDelete(true,5000.0f);
		}

		//! Destructor
		CProfiler::~CProfiler()
		{
			for(SectionsListType::Iterator Iter=Sections.begin();Iter!=Sections.end();Iter++)
				JEDELETE(*Iter)
			Sections.clear();

			SetProfiler(NULL);
		}

		//! Begin Section
		void CProfiler::BeginSection(jeStringc Name)
		{
			for(SectionsListType::Iterator Iter=Sections.begin();Iter!=Sections.end();Iter++)
				if((*Iter)->Name == Name)
				{
					(*Iter)->Open = true;
					(*Iter)->OpenTime = JETIME;
					return;
				}

			ProfileSection * Section = NULL;
			JENEW(Section,ProfileSection)
			Section->Name = Name;
			Section->Open = true;
			Section->OpenTime = JETIME;
			Sections.push_back(Section);
		}

		//! End Section
		void CProfiler::EndSection(jeStringc Name)
		{
			for(SectionsListType::Iterator Iter=Sections.begin();Iter!=Sections.end();Iter++)
				if((*Iter)->Name == Name)
				{
					(*Iter)->Open = false;
					(*Iter)->WorkTime = JETIME - (*Iter)->OpenTime;
					return;
				}
		}

		//! Set Auto Delete (by default, profiler delete all sections than open more than 5 secs)
		void CProfiler::SetAutoDelete(u1 Enable,f32 DelTime)
		{
			EnableDelete = Enable;
			DeleteTime = DelTime;
		}

		//! Loop Tick
		void CProfiler::LoopTick()
		{
			if(!EnableDelete)
				return;

			f32 Time = JETIME;
			for(SectionsListType::Iterator Iter=Sections.begin();Iter!=Sections.end();Iter++)
				if(((*Iter)->OpenTime - Time) > DeleteTime)
				{
					JEDELETE(*Iter)
						Iter = Sections.erase(Iter);
				}
		}
	}
}
